package cn.itcast.filter;

import cn.itcast.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

//@WebFilter("/*")
//@Component
public class LoginFilter implements Filter {
    //@Autowired
    private JwtUtils jwtUtils;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取请求数据
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        //获取响应数据
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        // 获取当前请求路径
        String requestURI = request.getRequestURI();
        //1.判断当前请求是否为登录请求
        if (requestURI.contains("/login")){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //2.判断当前请求是否有令牌
        String token = request.getHeader("token");
        if (token == null){
            response.setStatus(401);
            return;
        }
        //3.解析令牌有异常的情况
        try {
            Map<String, Object> payload = jwtUtils.parseToken(token);
        } catch (Exception e) {
            response.setStatus(401);
            return;
        }
        //满足条件放行
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
